package com.core.a.sample;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Sunil
 */
public class Multi {

    public static void main(String[] args) {
        List<Integer> list = new ArrayList<Integer>();
        Thread p1 = new Thread(new Producer(list));
        Thread c1 = new Thread(new Consumer(list, "one"));
        Thread c2 = new Thread(new Consumer(list, "two"));

        p1.start();
        c1.start();
        c2.start();
    }
}

class Producer implements Runnable {

    List<Integer> list;
    int count;

    public Producer(List<Integer> list) {
        this.list = list;
    }

    public void run() {
        while (true) {
            synchronized (list) {
                list.add(count++);
                list.notifyAll();
                System.out.println("PRODUCE : " + count);
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

        }

    }
}

class Consumer implements Runnable {

    List<Integer> list;
    String name;

    public Consumer(List<Integer> list, String name) {
        this.list = list;
        this.name = name;
    }

    public void run() {
        while (true) {
            System.out.println(name);
            synchronized (list) {
                if (!list.isEmpty()) {
                    System.out.println("CONSUME : " + name + " : " + list.remove(0));
                }
                try {
                    list.wait();
                } catch (InterruptedException ex) {
                    Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

        }
    }
}